//package com.css.cloudlearn.productornacos;
//
//import com.alibaba.fastjson.JSONArray;
//import com.css.dynamic.conanst.CacheConstants;
//import com.css.dynamic.dynamicRoute.RouteDefinitionVo;
//import com.css.dynamic.event.DynamicRouteInitEvent;
//import lombok.AllArgsConstructor;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.boot.web.context.WebServerInitializedEvent;
//import org.springframework.cloud.gateway.event.RefreshRoutesEvent;
//import org.springframework.cloud.gateway.filter.FilterDefinition;
//import org.springframework.cloud.gateway.handler.predicate.PredicateDefinition;
//import org.springframework.context.ApplicationEventPublisher;
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.context.event.EventListener;
//import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
//import org.springframework.core.annotation.Order;
//import org.springframework.data.redis.connection.RedisConnectionFactory;
//import org.springframework.data.redis.core.RedisTemplate;
//import org.springframework.data.redis.listener.ChannelTopic;
//import org.springframework.data.redis.listener.RedisMessageListenerContainer;
//import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
//import org.springframework.scheduling.annotation.Async;
//
//import java.net.URI;
//import java.util.ArrayList;
//import java.util.List;
//
///**
// * @author liyingbo
// * @date 2018/10/31
// * <p>
// * 容器启动后保存配置文件里面的路由信息到Redis
// */
//@Slf4j
//@Configuration
//@AllArgsConstructor
//public class DynamicRouteInitRunner {
//    private final RedisTemplate redisTemplate;
//    private final ApplicationEventPublisher applicationEventPublisher;
//
//    @Async
//    @Order
//    @EventListener({WebServerInitializedEvent.class, DynamicRouteInitEvent.class})
//    public void initRoute() {
//
//		/*Set<String> keys = redisTemplate.opsForHash().keys(CacheConstants.ROUTE_KEY);
//		if(keys!=null && keys.size()>0){
//			return;
//		}*/
//
//        Boolean result = redisTemplate.delete(CacheConstants.ROUTE_KEY);
//        log.info("初始化网关路由 {} ", result);
//
//        List<RouteConfEntity> routes = new ArrayList<RouteConfEntity>();
//		/*routes.add(new RouteConfEntity(1,"mass-demmo","样例微服务",
//				"[{\"args\": {\"_genkey_0\": \"/demo/**\"}, \"name\": \"Path\"}]",
//				"[]","lb://mass-demmo",0,null,null,"0"));*/
//        routes.add(new RouteConfEntity("mass-auth-biz", "mass-auth-biz", "认证中心",
//                "[{\"args\": {\"_genkey_0\": \"/AuthCenter/**\"}, \"name\": \"Path\"}]",
//                "[]", "lb://mass-auth-biz", 0, null, null, "0"));
//        routes.add(new RouteConfEntity("mass-user-biz", "mass-user-biz", "用户中心",
//                "[{\"args\": {\"_genkey_0\": \"/user-center/**\"}, \"name\": \"Path\"}]",
//                "[]", "lb://mass-user-biz", 0, null, null, "0"));
//        routes.add(new RouteConfEntity("mass-notice-biz", "mass-notice-biz", "消息中心",
//                "[{\"args\": {\"_genkey_0\": \"/notice-center/**\"}, \"name\": \"Path\"}]",
//                "[]", "lb://mass-notice-biz", 0, null, null, "0"));
//        routes.add(new RouteConfEntity("mass-log-biz", "mass-log-biz", "审计日志",
//                "[{\"args\": {\"_genkey_0\": \"/LogManager/**\"}, \"name\": \"Path\"}]",
//                "[]", "lb://mass-log-biz", 0, null, null, "0"));
//
//        System.out.println(com.alibaba.fastjson.JSONArray.toJSONString(routes));
//
//        routes.forEach(route -> {
//            RouteDefinitionVo vo = new RouteDefinitionVo();
//            vo.setRouteName(route.getRouteName());
//            vo.setId(route.getRouteId());
//            vo.setUri(URI.create(route.getUri()));
//            vo.setOrder(route.getOrder());
//
//            JSONArray filterObj = JSONUtil.parseArray(route.getFilters());
//            vo.setFilters(filterObj.toList(FilterDefinition.class));
//            JSONArray predicateObj = JSONUtil.parseArray(route.getPredicates());
//            vo.setPredicates(predicateObj.toList(PredicateDefinition.class));
//
//            log.info("加载路由ID：{},{}", route.getRouteId(), vo);
//            redisTemplate.setHashValueSerializer(new Jackson2JsonRedisSerializer<>(RouteDefinitionVo.class));
//            redisTemplate.opsForHash().put(CacheConstants.ROUTE_KEY, route.getRouteId(), vo);
//
//        });
//
//        try {
//            for (Integer i = 5; i >= 0; i--) {
//                Thread.sleep(1 * 1000);
//                log.info("初始化网关路由倒计时：" + i.toString() + "s");
//            }
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
//
//        this.applicationEventPublisher.publishEvent(new RefreshRoutesEvent(this));
//        redisTemplate.convertAndSend(CacheConstants.ROUTE_JVM_RELOAD_TOPIC, "UPMS路由信息,网关缓存更新");
//
//        log.info("初始化网关路由结束 ");
//    }
//
//    /**
//     * redis 监听配置,监听 gateway_redis_route_reload_topic,重新加载Redis
//     *
//     * @param redisConnectionFactory redis 配置
//     * @return
//     */
//    @Bean
//    public RedisMessageListenerContainer redisContainerServer(RedisConnectionFactory redisConnectionFactory) {
//        RedisMessageListenerContainer container
//                = new RedisMessageListenerContainer();
//        container.setConnectionFactory(redisConnectionFactory);
//        container.addMessageListener((message, bytes) -> {
//            log.warn("接收到重新Redis 重新加载路由事件");
//            initRoute();
//        }, new ChannelTopic(CacheConstants.ROUTE_REDIS_RELOAD_TOPIC));
//        return container;
//    }
//
//    @Bean
//    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
//        return new PropertySourcesPlaceholderConfigurer();
//    }
//
//}
